package com.example.seabedmusic.views;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.seabedmusic.R;
import com.example.seabedmusic.adapter.WoDeAdapter;
import com.example.seabedmusic.entity.Song;
import com.example.seabedmusic.entity.User;
import com.example.seabedmusic.utils.LocalMusicManager;
import com.example.seabedmusic.utils.PlaylistManager;
import com.example.seabedmusic.utils.RecentPlayManager;
import com.example.seabedmusic.utils.UserManager;

import java.util.ArrayList;
import java.util.List;

public class WoDeFragment extends Fragment implements WoDeAdapter.OnSongClickListener {
    private ImageView ivAvatar;
    private TextView tvName;
    private TextView tvLocalMusic;
    private TextView tvRecentTitle;
    private RecyclerView rvRecent;
    private TextView tvMyPlaylist;
    private ImageView ivSettings;

    private WoDeAdapter adapter;
    private RecentPlayManager recentPlayManager;
    private PlaylistManager playlistManager;
    private LocalMusicManager localMusicManager;
    private UserManager userManager;
    private List<Song> recentSongs = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_wode, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initViews(view);
        setupManagers();
        setupUserInfo(); // 修改：先设置用户信息
        setupAdapter();
        setupClickListeners();
    }

    private void initViews(View view) {
        ivAvatar = view.findViewById(R.id.ivAvatar);
        tvName = view.findViewById(R.id.tvName);
        tvLocalMusic = view.findViewById(R.id.tvLocalMusic);
        tvRecentTitle = view.findViewById(R.id.tvRecentTitle);
        rvRecent = view.findViewById(R.id.rvRecent);
        tvMyPlaylist = view.findViewById(R.id.tvMyPlaylist);
        ivSettings = view.findViewById(R.id.ivSettings);
    }

    private void setupManagers() {
        recentPlayManager = RecentPlayManager.getInstance(getContext());
        playlistManager = PlaylistManager.getInstance();
        localMusicManager = LocalMusicManager.getInstance(getContext());
        userManager = UserManager.getInstance(getContext()); // 新增：初始化用户管理器
    }

    /**
     * 修改：设置用户信息，显示登录的用户数据
     */
    private void setupUserInfo() {
        // 获取当前登录的用户信息
        User currentUser = userManager.getCurrentUser();

        if (currentUser != null) {
            // 显示用户昵称
            tvName.setText(currentUser.getNickname());

            // 加载用户头像
            if (currentUser.getAvatar() != null && !currentUser.getAvatar().isEmpty()) {
                Glide.with(this)
                        .load(currentUser.getAvatar())
                        .placeholder(R.drawable.ic_avatar_placeholder)
                        .error(R.drawable.ic_avatar_placeholder)
                        .into(ivAvatar);
            } else {
                // 如果没有头像，使用默认头像
                ivAvatar.setImageResource(R.drawable.ic_avatar_placeholder);
            }

            Log.d("WoDeFragment", "显示用户信息: " + currentUser.getNickname());
        } else {
            // 如果没有登录用户，显示默认信息
            tvName.setText("音乐玩家");
            ivAvatar.setImageResource(R.drawable.ic_avatar_placeholder);
            Log.d("WoDeFragment", "没有登录用户，显示默认信息");
        }
    }

    private void setupAdapter() {
        // 获取真实的最近播放数据
        recentSongs = recentPlayManager.getRecentSongs();
        Log.d("WoDeFragment", "最近播放歌曲数量: " + recentSongs.size());

        // 如果没有最近播放，显示默认数据（带封面）
        if (recentSongs.isEmpty()) {
            recentSongs = createDefaultSongs();
        }

        adapter = new WoDeAdapter(recentSongs);
        rvRecent.setLayoutManager(new LinearLayoutManager(getContext()));
        rvRecent.setAdapter(adapter);

        // 设置歌曲点击监听
        adapter.setOnSongClickListener(this);

        // 设置不是本地音乐页面
        adapter.setIsLocalMusic(false);
    }

    /**
     * 创建默认歌曲数据（带封面）
     */
    private List<Song> createDefaultSongs() {
        List<Song> defaultSongs = new ArrayList<>();

        Song song1 = new Song();
        song1.setTitle("晴天");
        song1.setArtist("周杰伦");
        song1.setCover("https://p2.music.126.net/ooKX41utUL93kqHRh2x16g==/109951168063075674.jpg");

        Song song2 = new Song();
        song2.setTitle("稻香");
        song2.setArtist("周杰伦");
        song2.setCover("https://p1.music.126.net/ooKX41utUL93kqHRh2x16g==/109951168063075674.jpg");

        Song song3 = new Song();
        song3.setTitle("夜曲");
        song3.setArtist("周杰伦");
        song3.setCover("https://p2.music.126.net/ooKX41utUL93kqHRh2x16g==/109951168063075674.jpg");

        defaultSongs.add(song1);
        defaultSongs.add(song2);
        defaultSongs.add(song3);

        return defaultSongs;
    }

    private void setupClickListeners() {
        tvLocalMusic.setOnClickListener(v -> {
            navigateToLocalMusic();
        });

        tvMyPlaylist.setOnClickListener(v -> {
            navigateToPlaylist();
        });

        ivSettings.setOnClickListener(v -> {
            navigateToSettings();
        });
    }

    /**
     * 跳转到设置页面
     */
    private void navigateToSettings() {
        Log.d("WoDeFragment", "跳转到设置页面");
        Intent intent = new Intent(getActivity(), SettingsActivity.class);
        startActivity(intent);
    }

    /**
     * 点击歌曲 - 跳转到播放页面
     */
    @Override
    public void onSongClick(Song song) {
        navigateToMusicPlayer(song);
    }

    /**
     * 更多按钮点击 - 显示操作菜单
     */
    @Override
    public void onMoreClick(Song song) {
        Log.d("WoDeFragment", "更多操作点击: " + song.getTitle());
    }

    private void navigateToMusicPlayer(Song song) {
        Intent intent = new Intent(getActivity(), MusicPlayerActivity.class);
        intent.putExtra("song_title", song.getTitle());
        intent.putExtra("song_artist", song.getArtist());
        intent.putExtra("song_url", song.getUrl());
        intent.putExtra("song_cover", song.getCover());
        intent.putExtra("song_album", song.getAlbum());
        intent.putExtra("song_lyrics", song.getLyrics());
        startActivity(intent);
    }

    private void navigateToLocalMusic() {
        Intent intent = new Intent(getActivity(), LocalMusicActivity.class);
        startActivity(intent);
    }

    private void navigateToPlaylist() {
        Log.d("WoDeFragment", "跳转我的歌单");
        Intent intent = new Intent(getActivity(), PlaylistActivity.class);
        startActivity(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshRecentSongs();
        refreshUserInfo(); // 新增：每次回到页面时刷新用户信息
    }

    /**
     * 刷新最近播放列表
     */
    private void refreshRecentSongs() {
        if (recentPlayManager != null && adapter != null) {
            List<Song> updatedSongs = recentPlayManager.getRecentSongs();

            if (updatedSongs.isEmpty()) {
                updatedSongs = createDefaultSongs();
            }

            adapter.updateData(updatedSongs);
            Log.d("WoDeFragment", "刷新最近播放，数量: " + updatedSongs.size());
        }
    }

    /**
     * 新增：刷新用户信息
     */
    private void refreshUserInfo() {
        if (userManager != null) {
            setupUserInfo(); // 重新设置用户信息
        }
    }
}